from login.models import Msg, UserProfile


def SendMsgToUser(sender, receiver, subject, contents):
    # 判断输入的是ID还是用户名
    try:
        sender = UserProfile.objects.get(id=sender)
    except UserProfile.DoesNotExist:
        # 获取不到，尝试获取用户名
        try:
            sender = UserProfile.objects.get(username=sender)
        except UserProfile.DoesNotExist:
            # 传入的不是用户名，也不是ID，则返回错误
            raise ValueError("站内信需要传入用户ID或者用户姓名！")
    try:
        receiver = UserProfile.objects.get(id=receiver)
    except UserProfile.DoesNotExist:
        # 获取不到，尝试获取用户名
        try:
            receiver = UserProfile.objects.get(username=receiver)
        except UserProfile.DoesNotExist:
            # 传入的不是用户名，也不是ID，则返回错误
            raise ValueError("站内信需要传入用户ID或者用户姓名！")
    new_Msg = Msg(receiver=receiver, sender=sender, subject=subject, contents=contents)
    new_Msg.save()
    return True
